package main

type ListNode struct {
	Val  int
	Next *ListNode
}

func getIntersectionNode(headA, headB *ListNode) *ListNode {
	nodeA := make([]*ListNode, 0)
	nodeB := make([]*ListNode, 0)

	temp := headA
	for temp != nil {
		nodeA = append(nodeA, temp)
		temp = temp.Next
	}
	temp = headB
	for temp != nil {
		nodeB = append(nodeB, temp)
		temp = temp.Next
	}

	nodeATail := len(nodeA) - 1
	nodeBTail := len(nodeB) - 1

	for nodeATail >= 0 && nodeBTail >= 0 {
		if nodeA[nodeATail] != nodeB[nodeBTail] {
			break
		}
	}

	if nodeATail == len(nodeA)-1 {
		return nil
	}

	return nodeA[nodeATail+1]
}
